import { Component, OnInit, Output, Input, EventEmitter } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd';
import { _HttpClient } from '@delon/theme';
import { HttpParams } from '@angular/common/http';
import { environment } from '../../../../environments/environment';

@Component({
    selector: 'app-addwork',
    templateUrl: './addwork.component.html',
    styles: [`
        .red{color:#ff0000}
        .w95{width:95%}
        :host ::ng-deep .ant-select-selection--multiple{min-height:60px;overflow:hidden}
    `]
})
export class AddWorkComponent implements OnInit {
    Visible = false;
    workData: any = [];
    gradeData: any = [];
    typeData: any = [];
    devTypeLevel: any = [];
    workList: any = {
        'name': '', 'grade': [], 'circle': '', 'count': '', 'level': '', 'desc': '', 'unit': '', 'unitTime': '', 'topway': '', 'skylight': ''
    };
    circle: any = [];
    workId = '';
    workSearch = '';
    editStatus = false;
    treeNodeStyle = { 'max-width': '400px', 'max-height': '400px', 'overflow-y': 'auto', 'overflow-x': 'hidden' };
    @Input() addWorkYearPlaceId: any;
    @Input() addWorkYearNid: any;
    @Output() public addWorkCloseModal = new EventEmitter();
    @Output() public addWorkReloadData = new EventEmitter();

    constructor(
        private message: NzMessageService,
        private http: _HttpClient
    ) { }

    ngOnInit() {
        this.workload(() => {
            // to do
        });
        this.circle = [
            { 'value': '10', 'label': '按需' },
            { 'value': '0', 'label': '每日' },
            { 'value': '5', 'label': '每周2次' },
            { 'value': '1', 'label': '每周' },
            { 'value': '2', 'label': '半月' },
            { 'value': '3', 'label': '每月' },
            { 'value': '6', 'label': '两月' },
            { 'value': '7', 'label': '三月' },
            { 'value': '8', 'label': '四月' },
            { 'value': '9', 'label': '六月' },
            { 'value': '4', 'label': '每年' },
            { 'value': '2y', 'label': '两年' },
            { 'value': '3y', 'label': '三年' },
            { 'value': '5y', 'label': '五年' }
        ];
        this.workList.topway = '1';
        this.workList.skylight = '1';
        setTimeout(() => {
            this.Visible = true;
        }, 200);
    }
    countcircleChange(e) {
        let circle = '';
        for (const item of this.circle) {
            if (item.value === this.workList.circle) {
                circle = item.label;
                break;
            }
        }
        this.workList.desc = circle + this.workList.count + '次';
    }
    workload(callback) {
        this.http.get(environment.apiBase + '/csmis/jxProjects/getAllJxProjects.jwt?place=' + this.addWorkYearPlaceId).subscribe((res: any) => {
            this.workData = this.formatTreeNode(res, 'work');
            this.typeData = this.formatTreeNode(res, 'worktype');
            callback();
        });
    }
    formatTreeNode(resdata, type) {
        const node: any = [];
        const pid: any = [];
        for (let i = 0; i < resdata.length; i++) {
            if (resdata[i].children) {
                node.push({
                    title: resdata[i].text,
                    key: resdata[i].id,
                    disabled: true,
                    children: []
                });
                for (let j = 0; j < resdata[i].children.length; j++) {
                    if (type === 'work') {
                        if (resdata[i].children[j]) {
                            node[i].children.push({
                                title: resdata[i].children[j].text,
                                key: resdata[i].children[j].id,
                                disabled: true,
                                children: []
                            });
                            for (const k of resdata[i].children[j].children) {
                                node[i].children[j].children.push({
                                    title: k.text,
                                    key: k.id,
                                    isLeaf: true
                                });
                            }
                        } else {
                            node[i].children.push({
                                title: resdata[i].children[j].text,
                                key: resdata[i].children[j].id,
                                isLeaf: true
                            });
                        }
                    } else {
                        node[i].children.push({
                            title: resdata[i].children[j].text,
                            key: resdata[i].children[j].state,
                            isLeaf: true
                        });
                        if (resdata[i].children[j].pid === '0') {
                            pid.push({ value: resdata[i].children[j].id, label: resdata[i].children[j].text });
                        }
                    }
                }
            } else {
                if (type === 'work') {
                    node.push({
                        title: resdata[i].text,
                        key: resdata[i].id,
                        isLeaf: true
                    });
                } else {
                    node.push({
                        title: resdata[i].text,
                        key: resdata[i].state,
                        isLeaf: true
                    });
                    if (resdata[i].pid === '0') {
                        pid.push({ value: resdata[i].id, label: resdata[i].text });
                    }
                }

            }
        }
        if (type === 'worktype') {
            return pid;
        } else {
            return node;
        }
    }
    edit() {
        // 作业项目树搜索不到的话，则把搜索关键字赋值给作业项目名称。官方没有API只有手写获取CLASS属性赋值
        const workSearch = document.getElementsByClassName('ant-select-search__field__mirror')[0].innerHTML.replace('&nbsp;', '');
        if (workSearch !== '') {
            this.workList.name = workSearch;
        }
        this.editStatus = true;
        this.http.get(environment.apiBase + '/csmis/devtypelevel/getDevTypeLevel.jwt').subscribe((res: any) => {
            this.devTypeLevel = res;
            this.gradeData = this.formatTreeNode(res, 'dev');
        });

    }
    back() {
        this.editStatus = false;
    }
    Ok() {
        if (this.workId === '') {
            this.message.create('error', '请选择作业项目');
            return;
        }
        const params = new HttpParams()
            .set('yaerId', this.addWorkYearNid)
            .set('projectId', this.workId);

        this.http.post(environment.apiBase + '/csmis/ymyear/ymtyearwork/addYearProjects.jwt', params).subscribe((res: any) => {
            if (res.type === "success") {
                this.message.create('success', '新增成功');
                this.addWorkReloadData.emit();
            } else {
                this.message.create('error', '新增失败');
            }
            this.Visible = false;
            setTimeout(() => {
                this.addWorkCloseModal.emit();
            }, 200);
        });
    }
    Cancel() {
        this.Visible = false;
        setTimeout(() => {
            this.addWorkCloseModal.emit();
        }, 200);
    }
    saveAll(inYearwork) {
        if (this.workList.name === '' || !this.workList.grade.length) {
            this.message.create('error', '必填项不能为空');
            return;
        }
        let devType = '';
        let devLevel = '';
        let devTypeLevel = '';
        for (const item of this.workList.grade) {
            for (const list of this.devTypeLevel) {
                if (list.children) {
                    for (const data of list.children) {
                        if (data.state === item) {
                            devType += ',' + data.id;
                            devLevel += ',' + data.tempCode;
                            devTypeLevel += ',' + data.text;
                        }
                    }
                }
            }
        }
        const params = new HttpParams()
            .set('pId', this.workList.type)
            .set('name', this.workList.name)
            .set('times', this.workList.count)
            .set('period', this.workList.circle)
            .set('devType', devType.replace(',', ''))
            .set('devLevel', devLevel.replace(',', ''))
            .set('shangdao', this.workList.topway)
            .set('skywin', this.workList.skylight)
            .set('sywz', '0' + this.addWorkYearPlaceId)// 只在这个接口补零
            .set('nClassId', this.workList.type)// 取pId的值
            .set('vcLevel', '')
            .set('vcRecycleDesc', this.workList.desc)
            .set('vcUnit', this.workList.unit)
            .set('devTypeLevel', devTypeLevel.replace(',', ''))
            .set('inYearwork', inYearwork)
            .set('yearId', this.addWorkYearNid);

        this.http.post(environment.apiBase + '/csmis/jxProjects/addProjectForYearWork.jwt', params).subscribe((res: any) => {
            if (res.type === "success") {
                switch (inYearwork) {
                    case '0':
                        this.back();
                        this.workload(() => {
                            // 返回作业项目并选中
                            for (const item of this.workData) {
                                if (item.children) {
                                    for (const list of item.children) {
                                        if (list) {
                                            for (const data of list.children) {
                                                if (data.title === this.workList.name) {
                                                    this.workId = data.key;
                                                    return;
                                                }
                                            }
                                        } else {
                                            if (list.title === this.workList.name) {
                                                this.workId = list.key;
                                                return;
                                            }
                                        }
                                    }
                                } else {
                                    if (item.title === this.workList.name) {
                                        this.workId = item.key;
                                        return;
                                    }
                                }
                            }
                        });
                        break;
                    case '1':
                        this.message.create('success', '新增成功');
                        this.addWorkReloadData.emit();
                        this.Visible = false;
                        setTimeout(() => {
                            this.addWorkCloseModal.emit();
                        }, 200);
                        break;
                }
            } else {
                this.message.create('error', res.message);
            }
        });
    }
}